from decimal import Decimal
from django.shortcuts import render
from rest_framework.generics import GenericAPIView,CreateAPIView
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
# Create your views here.
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from goods.models import SKU
from orders.serializers import CartSKUSerializer, OrderSettlementSerializer, SaveOrderSerializer
from datetime import datetime

class OrderSettlementView(GenericAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = OrderSettlementSerializer
    def get(self,request):
        # 1.从redis中获取选中的sku_id,selected,count
        user_id = request.user.id
        conn = get_redis_connection('cart')
        # pl = conn.pipeline()

        sku_list = conn.smembers("carts_selected_%s"%user_id)
        # sku_list = conn.smembers('carts_selected_%s'%user_id)
        print(sku_list)
        cart_dict = conn.hgetall('carts_%s'%user_id)
        # pl.execute()
        cart = {}
        # for sku_id in cart_dict.keys():
        #     if sku_id in sku_list:
        #         cart[int(sku_id)] = int(cart_dict[sku_id])
        for sku_id in sku_list:
            print(sku_id)

            cart[int(sku_id)] = int(cart_dict[sku_id])
        # 2.获取选中的sku_id在SKU表的对象查询集
        skus = SKU.objects.filter(id__in=cart.keys())


        # 3.遍历skus查询集，在每个sku对象加上count属性
        for sku in skus:
            sku.count = cart[sku.id]
            print(sku.count)
            sku.selected = True

        # 运费
        freight = Decimal('10.00')
        # 4.序列化返回
        ser = self.serializer_class({'freight':freight,'skus':skus})

        return Response(ser.data)




class SaveOrderView(CreateAPIView):

    permission_classes = [IsAuthenticated]
    serializer_class = SaveOrderSerializer










